package org.example.common.util;

import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * bean 拷贝工具类
 */
@UtilityClass
public class BeanCopyUtil extends BeanUtils {

    @SneakyThrows
    public static <S, T> T copy(S source, Class<T> clazz) {
        if (Objects.isNull(clazz) || Objects.isNull(source)) {
            return null;
        }
        T t = clazz.getDeclaredConstructor().newInstance();
        copyProperties(source, t);
        return t;
    }

    public static <S, T> T copy(S source, Supplier<T> target) {
        if (Objects.isNull(source)) {
            return null;
        }
        T t = target.get();
        copyProperties(source, t);
        return t;
    }

    public static <S, T> List<T> copyList(Collection<S> sources, Supplier<T> target) {
        if (CollectionUtils.isEmpty(sources)) {
            return new ArrayList<>();
        }
        List<T> list = new ArrayList<>(sources.size());
        for (S source : sources) {
            T t = target.get();
            copyProperties(source, t);
            list.add(t);
        }
        return list;
    }

    @SneakyThrows
    public static <S, T> List<T> copyList(Collection<S> sources, Class<T> clazz) {
        if (CollectionUtils.isEmpty(sources)) {
            return new ArrayList<>();
        }
        List<T> list = new ArrayList<>(sources.size());
        for (S source : sources) {
            T t = clazz.getDeclaredConstructor().newInstance();
            copyProperties(source, t);
            list.add(t);
        }
        return list;
    }
}
